/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package downloadmanager.downloader;

import java.io.*;
import java.net.*;

/**
 *
 * @author Administrator
 */
public class HttpProtocolProvider {

    public InputStream createStream(URL url, long initialPosition, long endPosition) throws Exception {
        HttpURLConnection request = (HttpURLConnection) url.openConnection();

        if (initialPosition != 0) {
            if (endPosition == 0) {
                request.setRequestProperty("Range", String.format("bytes=%d-", initialPosition));
            } else {
                request.setRequestProperty("Range", String.format("bytes=%d-%d", initialPosition, endPosition));
            }
        }

        return request.getInputStream();
    }

    public InputStream createStream(String url, long initialPosition, long endPosition) throws Exception {
        return createStream(new URL(url), initialPosition, endPosition);
    }

    public RemoteFileInfo getFileInfo(URL url, InputStream[] stream) throws Exception {
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        RemoteFileInfo result = new RemoteFileInfo();
        result.setMimeType(request.getContentType());
        result.setLastModified(request.getLastModified());
        result.setFileSize(request.getContentLength());
        result.setAcceptRanges(request.getHeaderField("Accept-Ranges").equalsIgnoreCase("bytes"));

        stream[0] = request.getInputStream();

        return result;
    }

    public RemoteFileInfo getFileInfo(String url, InputStream[] stream) throws Exception {
        return getFileInfo(new URL(url), stream);
    }
}
